﻿#region

using System.Collections.Generic;
using System.Linq;
using CuongHanh.DAL;
using CuongHanh.Models;

#endregion

namespace CuongHanh.Context
{
    public class CacheList<T>
            where T : BaseClass1, new()
    {
        public static CacheList<T> Singleton = new CacheList<T>();

        private readonly Dictionary<int, Dictionary<int, T>> _caches = new Dictionary<int, Dictionary<int, T>>();

        private readonly object _lockCache = new object();

        public CacheList()
        {
            LoadCache();
        }

        private void LoadCache()
        {
            lock (_lockCache)
            {
                using (UnitOfWork unitOfWork = new UnitOfWork())
                {
                    IQueryable<T> models = unitOfWork.Where<T>();
                    foreach (T model in models)
                    {
                        if(!_caches.ContainsKey(model.Key1))
                            _caches[model.Key1] = new Dictionary<int, T>();
                        _caches[model.Key1][model.Key2] = model;
                    }
                }
            }
        }

        public IEnumerable<T> GetCache(int key1)
        {
            lock (_lockCache)
            {
                return _caches.ContainsKey(key1)
                        ? _caches[key1].Values.ToList()
                        : new List<T>();
            }
        }

        public T GetCache(int key1,
                int key2)
        {
            lock (_lockCache)
            {
                if(_caches.ContainsKey(key1)
                   && _caches[key1].ContainsKey(key2))
                    return _caches[key1][key2];
                return null;
            }
        }

        public bool DeleteCache(T model)
        {
            lock (_lockCache)
            {
                if(!_caches.ContainsKey(model.Key1)
                   || !_caches[model.Key1].ContainsKey(model.Key2))
                    return false;
                _caches[model.Key1].Remove(model.Key2);
                return true;
            }
        }

        public bool UpdateCache(T model)
        {
            lock (_lockCache)
            {
                if(!_caches.ContainsKey(model.Key1))
                    _caches[model.Key1] = new Dictionary<int, T>();

                _caches[model.Key1][model.Key2] = model;
                return true;
            }
        }
    }
}
